<template>
  <!-- 产品类别 -->
  <p-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button @click="openAddBtn" type="primary" icon="plus">新增</p-button>

      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
        <p-button
          v-if=" item.optType=='js' && (item.groupTag == null || item.groupTag == '' )"
          :key=" 'cgbtn'+index "
          @click="cgButtonJsHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
        <p-button
          v-else-if=" item.optType=='action' && (item.groupTag == null || item.groupTag == '' )"
          :key=" 'cgbtn'+index "
          @click="cgButtonActionHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
      </template>

      <!-- 高级查询区域 -->
      <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query>

      <p-dropdown v-for="(item,index) in groupTag" :key="index">
        <p-button>
          {{item.name}}
          <p-icon type="down" />
        </p-button>
        <p-menu slot="overlay">
          <template v-for="(items,indexs) in item.data">
            <p-menu-item
              v-if=" items.optType=='js' "
              :key="indexs"
              @click="cgButtonJsHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />
              {{items.buttonName}}
            </p-menu-item>
            <p-menu-item
              v-else-if=" items.optType=='action' "
              :key="indexs"
              @click="cgButtonActionHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />
              {{items.buttonName}}
            </p-menu-item>
          </template>
        </p-menu>
      </p-dropdown>

      <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel">
            <p-icon type="delete" />删除
          </p-menu-item>
        </p-menu>
        <p-button style="margin-center: 8px">
          批量操作
          <p-icon type="down" />
        </p-button>
      </p-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-center: 24px" @click="onClearSelected">清空</a>

        <span style="float:right;">
          <a @click="handleExportXls('产品缺陷管理-类别管理-产品类别')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a>
              <p-icon type="import" />导入
            </a>
          </p-upload>
          <p-divider type="vertical" />

          <a @click="loadData()">
            <p-icon type="sync" />刷新
          </a>
          <p-divider type="vertical" />
          <p-popover title="自定义列" trigger="click" placement="centerBottom" :overlay-style="getWidth">
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item,index) in defColumns">
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                      <p-col :span="12">
                        <p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a>
              <p-icon type="setting" />自定义列
            </a>
          </p-popover>
        </span>
      </div>

      <p-table
        ref="table"
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        :customRow="clickThenSelect"
        :rowClassName="setRowClassName"
        @change="handleTableChange"
        @expand="handleExpand"
        v-bind="tableProps"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt="图片不存在"
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
          <p-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)"
          >下载</p-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="openEditBtn(record)">编辑</a>
           <p-divider type="vertical" />

<a @click="openAddChildBtn(record)">新增子节点</a>
          <p-divider type="vertical" />
          <p-dropdown>
            <a class="ant-dropdown-link">
              更多
              <p-icon type="down" />
            </a>
            <p-menu slot="overlay">
              <p-menu-item>
                <p-popconfirm title="确定删除吗?" @confirm="() => proOpeDel(record.id)">
                  <a>删除</a>
                </p-popconfirm>
              </p-menu-item>
              <template
                v-if="cgButtonLinkList && cgButtonLinkList.length>0"
                v-for="(btnItem,btnIndex) in cgButtonLinkList"
              >
                <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                  <a
                    href="javascript:void(0);"
                    @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)"
                  >
                    <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                    {{ btnItem.buttonName }}
                  </a>
                </p-menu-item>
              </template>
            </p-menu>
          </p-dropdown>
        </span>
      </p-table>
    </div>

    <mesQcProductType-modal ref="modalForm" :EnhanceJS="EnhanceJS" @ok="modalFormOk"></mesQcProductType-modal>


    <p-modal v-model="pModalVisible" :title="ptitle" :width="900" @ok="pModalOkBtn">

        <p-form :form="pForm">
          <p-row>

            <p-col  :span="24">
              <p-form-item label="父层级" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <p-input v-decorator="[ 'pid', validatorRules.pid]" placeholder="请选择父层级" disabled></p-input>
              </p-form-item>
            </p-col>




            <p-col  :span="24">
              <p-form-item label="产品类别层级编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <p-input v-decorator="[ 'productHierarchyCode', validatorRules.productHierarchyCode]" placeholder="请输入产品类别层级编码"></p-input>
              </p-form-item>
            </p-col>

            <p-col  :span="24">
              <p-form-item label="产品层级名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <p-input v-decorator="[ 'productHierarchyName', validatorRules.productHierarchyName]" placeholder="请输入产品层级名称"></p-input>
              </p-form-item>
            </p-col>

            <p-col  :span="24">
              <p-form-item label="产品层级描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <p-input v-decorator="[ 'productHierarchyDescribe', validatorRules.productHierarchyDescribe]" placeholder="请输入产品层级描述"></p-input>
              </p-form-item>
            </p-col>

            <p-col  :span="24">
              <p-form-item label="产品层级" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <p-input v-decorator="[ 'productHierarchy', validatorRules.productHierarchy]" placeholder="请选择产品层级" disabled></p-input>
              </p-form-item>
            </p-col>

            <p-col  :span="24">
              <p-form-item label="产品类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <!--<j-dict-select-tag type="list" v-decorator="['productType', validatorRules.productType]" :trigger-change="true" dictCode="produce_type" placeholder="请选择产品类别"/>-->
                <p-select v-decorator="['productType', validatorRules.productType]"  placeholder="请选择产品类别">
                    <p-select-option :value='1'>成品</p-select-option>
                    <p-select-option :value='2'>模块</p-select-option>
                    <p-select-option :value='3'>PCBA</p-select-option>
                </p-select>
              </p-form-item>
            </p-col>
          </p-row>

        </p-form>

    </p-modal>


    <!-- 弹出窗 -->
    <Fx-compontens-modal
      @ok="modalFormOk"
      ref="modalCompon"
      :getList="queryInfo"
      :title="title"
      :dictOptions="dictOptions"
    ></Fx-compontens-modal>
  </p-card>
</template>

<script>
import { api } from "@/api/manage";
import Vue from "vue";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj } from "@/utils/util";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import MesQcProductTypeModal from "./modules/MesQcProductTypeModal";

import  dayjs   from 'dayjs';
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction,putAction } from "@/api/manage";
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";

//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "pid",
    text: "父层级",
    type: "string",
  },
  {
    value: "productHierarchyCode",
    text: "产品类别层级编码",
    type: "String",
  },
  {
    value: "productHierarchyName",
    text: "产品层级名称",
    type: "String",
  },
  {
    value: "productHierarchyDescribe",
    text: "产品层级描述",
    type: "String",
  },
  {
    value: "productHierarchy",
    text: "产品层级",
    type: "select",
    dictCode: "product_hierarchy",
  },
  {
    value: "productType",
    text: "产品类别",
    type: "select",
    dictCode: "produce_type",
  },
  {
    value: "createTime",
    text: "创建日期",
    type: "Date",
  },
  {
    value: "createBy",
    text: "创建人",
    type: "string",
  },
  {
    value: "updateTime",
    text: "更新日期",
    type: "Date",
  },
  {
    value: "updateBy",
    text: "更新人",
    type: "string",
  },
];

export default {
  name: "MesQcProductTypeList",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    FxCompontensModal,
    MesQcProductTypeModal,
  },
  data() {
    return {
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      superQueryParams: "",
      EnhanceJS: "",
      description: "产品缺陷管理-类别管理-产品类别管理页面",
      cgButtonLinkList: [],
      title: "", //存表名
      cgButtonList: [],
      groupTag: [],
      queryInfo: [],

      currentState:1,
      currentEditP:{},

      rowId:0,

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },


      pForm:this.$form.createForm(this),

      validatorRules: {
        pid: {rules: [
          ]},
        productHierarchyCode: {rules: [
            {required: true, message: '请输入产品类别层级编码!'},
          ]},
        productHierarchyName: {rules: [
            {required: true, message: '请输入产品层级名称!'},
          ]},
        productHierarchyDescribe: {rules: [
            {required: true, message: '请输入产品层级描述!'},
          ]},
        productHierarchy: {rules: [
            {required: true, message: '请输入产品层级!'},
          ]},
        productType: {rules: [

          ]},
      },

      pModalVisible:false,

      ptitle:'',


      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "产品类别层级编码",
          align: "center",
          dataIndex: "productHierarchyCode",
        },
        {
          title: "产品层级名称",
          align: "center",
          dataIndex: "productHierarchyName",
        },
        {
          title: "产品层级描述",
          align: "center",
          dataIndex: "productHierarchyDescribe",
        },
        {
          title: "产品层级",
          align: "center",
          dataIndex: "productHierarchy",
        },
        {
          title: "产品类别",
          align: "center",
          dataIndex: "productType",
          customRender: (text) => {

            if (!text) {
              return "";
            } else {
              let result = '';
              switch (text) {
                  case 1:
                    result = '成品';
                    break;
                case 2:
                  result = '模块';
                  break;
                case 3:
                  result = 'PCBA';
                  break;
                  default:
                    result = '';
                    break;
              }

              return result;
            }
          },
        },
        {
          title: "创建日期",
          align: "center",
          dataIndex: "createTime",
          customRender: (text) => {
            let textStr = text+'';
            if(textStr.indexOf('-')==-1){
              return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
            }else{
              return text;
            }
          }
        },
        {
          title: "创建人",
          align: "center",
          dataIndex: "createBy",
        },
        {
          title: "更新日期",
          align: "center",
          dataIndex: "updateTime",
          customRender: (text) => {
            let textStr = text+'';
            if(textStr.indexOf('-')==-1){
              return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
            }else{
              return text;
            }
          }
        },
        {
          title: "更新人",
          align: "center",
          dataIndex: "updateBy",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list: "/mes-quality/mesQcProductType/rootList",
        childList: "/mes-quality/mesQcProductType/childList",
        delete: "/mes-quality/mesQcProductType/delete",
        deleteBatch: "/mes-quality/mesQcProductType/deleteBatch",
        exportXlsUrl: "/mes-quality/mesQcProductType/exportXls",
        importExcelUrl: "/mes-quality/mesQcProductType/importExcel",
        getColumns: "/mes-quality/online/cgform/api/getColumns/",
        buttonAction: "/mes-quality/online/cgform/api/doButton",
      },
      expandedRowKeys: [],
      hasChildrenField: "hasChild",
      pidField: "pid",
      dictOptions: {},
    };
  },
  computed: {
    importExcelUrl() {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    tableProps() {
      let _this = this;
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) =>
            (_this.selectedRowKeys = selectedRowKeys),
        },
      };
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
  },



  created() {
    this.initButtonList();
    this.initColumns();
  },

  methods: {
    onSelectChange(selectedRowKeys, selectionRows) {
      this.rowId = 0,
              this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            if(record.id){
              console.log(record.id)
              this.rowId = record.id;
             /* this.selectedRowKeys = [];
              this.selectionRows = [];*/
              //this.onSelectChange(record.id.split(","), [record]);
            }

          },
        },
      };
    },
    setRowClassName(record){
      return record.id === this.rowId ? 'clickRowStyl' : '';
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },


    dicgetMap(text){
      if (!text) {
        return "";
      } else {
        let result = '';
        switch (text) {
          case 1:
            result = '成品';
            break;
          case 2:
            result = '模块';
            break;
          case 3:
            result = 'PCBA';
            break;
          default:
            result = '';
            break;
        }

        return result;
      }
    },

    proOpeDel(id){

      deleteAction('/mes-quality/mesQcProductType/delete/'+id).then(res=>{
        if(res.success){
          this.$message.success("删除成功");
          this.loadData();
        }else{
          this.$message.warning("删除失败");
        }
      })
    },


    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },
    // 获取查询条件
    getQueryParams() {
      let sqp = {};
      if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },
    loadData(arg) {
      if (arg == 1) {
        this.ipagination.current = 1;
      }
      this.loading = true;
      this.expandedRowKeys = [];
      let params = this.getQueryParams();
      return new Promise((resolve) => {
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            let result = res.data;
            if (Number(result.total) > 0) {
              this.ipagination.total = Number(result.total);
              this.dataSource = this.getDataByResult(res.data.records);
              resolve();
            } else {
              this.ipagination.total = 0;
              this.dataSource = [];
            }
          } else {
            this.$message.warning(res.msg);
          }

          let dataSource = this.dataSource;

          dataSource.forEach(item=>{
            item = this.resetDataSource(item);
          })
          this.dataSource = dataSource;

          this.loading = false;
        });
      });




    },

    resetDataSource(data){
      if(data.children.length==0){
        delete data.children;
      }else{
        data.children.forEach(item=>{
          this.resetDataSource(item);
        })
      }
      return data;
    },


    openAddBtn(){
      this.ptitle = '新增';
      this.pModalVisible = true;
      this.currentState = 1;
      this.productType = {},
      setTimeout(()=>{
        this.pForm.setFieldsValue(
                {pid:'',
                  productHierarchyName:'',
                  productHierarchyCode:'',
                  productHierarchyDescribe:'',
                  productHierarchy:1,
                  productType:''
                }
        )
      },0)

    },

    openAddChildBtn(record){
      this.currentEditP = record;
      this.ptitle = '新增子节点';
      this.pModalVisible = true;
      this.currentState = 3;
      this.productType = {},
              setTimeout(()=>{
                this.pForm.setFieldsValue(
                        {pid:record.productHierarchyName,
                          productHierarchyName:'',
                          productHierarchyCode:'',
                          productHierarchyDescribe:'',
                          productHierarchy:record.productHierarchy+1,
                          productType:''
                        }
                )
              },0)
    },

   /* productHierarchyCode: {rules: [
        {required: true, message: '请输入产品类别层级编码!'},
      ]},
    productHierarchyName: {rules: [
        {required: true, message: '请输入产品层级名称!'},
      ]},
    productHierarchyDescribe: {rules: [
        {required: true, message: '请输入产品层级描述!'},
      ]},
    productHierarchy: {rules: [
        {required: true, message: '请输入产品层级!'},
      ]},
    productType: {rules: [*/

    openEditBtn(record){
      this.currentEditP = record;
      this.ptitle = '编辑';
      this.pModalVisible = true;
      this.currentState = 2;


      setTimeout(()=>{
        this.pForm.setFieldsValue(
                {pid:record.parentName,
                  productHierarchyName:record.productHierarchyName,
                  productHierarchyCode:record.productHierarchyCode,
                  productHierarchyDescribe:record.productHierarchyDescribe,
                  productHierarchy:record.productHierarchy,
                  productType:record.productType
                }
        )
      },0)
    },



    pModalOkBtn(e){
      e.preventDefault();
      this.pForm.validateFields((err, values) => {
        if (!err) {


          if(this.currentState==1){
            this.pOpeAdd(values);

          }else if(this.currentState==2){
          this.pOpeEdit(values);

          }else{
            this.pOpeAddChild(values);
          }

        }
      });


    },

    pOpeAddChild(value){

      let data={
        pid:this.currentEditP.id,
      }

      data.productHierarchyName = value.productHierarchyName;
      data.productHierarchyCode = value.productHierarchyCode;
      data.productHierarchyDescribe = value.productHierarchyDescribe;
      data.productHierarchy = value.productHierarchy;
      data.productType = value.productType;

      postAction('/mes-quality/mesQcProductType/add',data).then(res=>{
        if(res.success){
          this.pModalVisible = false;
          this.$message.success("新增成功！");
          this.loadData();
        }else{
          this.$message.warning("新增失败");
        }
      })
    },



    pOpeAdd(value){

        postAction('/mes-quality/mesQcProductType/add',value).then(res=>{
          if(res.success){
            this.pModalVisible = false;
            this.$message.success("新增成功！");
            this.loadData();
          }else{
            this.$message.warning("新增失败");
          }
        })
    },

    pOpeEdit(value){
      console.log('edit..............')
      let data = this.currentEditP;
      data.productHierarchyName = value.productHierarchyName;
      data.productHierarchyCode = value.productHierarchyCode;
      data.productHierarchyDescribe = value.productHierarchyDescribe;
      data.productHierarchy = value.productHierarchy;
      data.productType = value.productType;

      putAction('/mes-quality/mesQcProductType/edit',data).then(res=>{
        if(res.success){
          this.pModalVisible = false;
          this.$message.success("保存成功！");
          this.loadData();
        }else{
          this.$message.warning("保存失败");
        }
      })
    },



    getDataByResult(result) {
      return result.map((item) => {
        //判断是否标记了带有子节点
        if (item[this.hasChildrenField] == "1") {
          let loadChild = {
            id: item.id + "_loadChild",
            name: "loading...",
            isLoading: true,
          };
          item.children = [loadChild];
        }
        return item;
      });
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id);
        if (
          record.children.length > 0 &&
          record.children[0].isLoading === true
        ) {
          let params = this.getQueryParams(); //查询条件
          params[this.pidField] = record.id;
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.data && res.data.length > 0) {
                record.children = this.getDataByResult(res.data);
                this.dataSource = [...this.dataSource];
              } else {
                record.children = "";
                record.hasChildrenField = "0";
              }
            } else {
              this.$message.warning(res.msg);
            }
          });
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id);
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1);
        }
      }
    },
    initDictConfig() {},

    // 弹出窗组件
    showDemoModal() {
      this.$refs.modalCompon.modalShow();
    },
    // 点击btn获取数据
    btnGetData(tableName, title) {
      getAction(`${this.url.getColumns}`, {
        tableName: tableName,
      }).then((res) => {
        if (res.code == 0) {
          this.queryInfo = res.data.columns;
          this.title = title;
          this.dictOptions = res.data.dictOptions;
          this.showDemoModal();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    //筛选分组
    getGroupTag(arrList) {
      let arr = [];
      var map = {},
        dest = [];
      arrList.forEach((item, index) => {
        if (item.groupTag) {
          arr.push(item);
        }
      });
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.groupTag]) {
          dest.push({
            groupTag: ai.groupTag,
            name: ai.groupName,
            data: [ai],
          });
          map[ai.groupTag] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.groupTag == ai.groupTag) {
              dj.data.push(ai);
              break;
            }
          }
        }
      }
      this.groupTag = dest;
      console.log(dest);
    },
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    initButtonList() {
      getAction(`${this.url.getColumns}244c0544c62f49e28a731b434debeb86`).then(
        (res) => {
          console.log("--获取自定义按钮->>", res);
          if (res.success) {
            this.code = res.data.code;
            this.initCgButtonList(res.data.cgButtonList);
            this.initCgEnhanceJs(res.data.enhanceJs);
            this.getGroupTag(res.data.cgButtonList);
          } else {
            this.$message.warning(res.msg);
          }
        }
      );
    },
    initCgEnhanceJs(enhanceJs) {
      //console.log("--onlineList-js增强",enhanceJs)
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        console.log("自定义按钮link请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },
    modalFormOk(formData, arr) {
      if (!formData.id) {
        this.addOk(formData, arr);
      } else {
        if (!arr) {
          this.loadData();
        } else {
          this.editOk(formData, this.dataSource);
          this.dataSource = [...this.dataSource];
        }
      }
    },
    editOk(formData, arr) {
      if (arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == formData.id) {
            arr[i] = formData;
            break;
          } else {
            this.editOk(formData, arr[i].children);
          }
        }
      }
    },
    async addOk(formData, arr) {
      if (!formData[this.pidField]) {
        this.loadData();
      } else {
        this.expandedRowKeys = [];
        for (let i of arr) {
          await this.expandTreeNode(i);
        }
      }
    },
    expandTreeNode(nodeId) {
      return new Promise((resolve, reject) => {
        this.getFormDataById(nodeId, this.dataSource);
        let row = this.parentFormData;
        this.expandedRowKeys.push(nodeId);
        let params = this.getQueryParams(); //查询条件
        params[this.pidField] = nodeId;
        getAction(this.url.childList, params).then((res) => {
          if (res.success) {
            if (res.data && res.data.length > 0) {
              row.children = this.getDataByResult(res.data);
              this.dataSource = [...this.dataSource];
              resolve();
            } else {
              reject();
            }
          } else {
            reject();
          }
        });
      });
    },
    getFormDataById(id, arr) {
      if (arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == id) {
            this.parentFormData = arr[i];
          } else {
            this.getFormDataById(id, arr[i].children);
          }
        }
      }
    },
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
/deep/.clickRowStyl td{
  background:#00b4ed !important;
}

/deep/.ant-table-tbody.clickRowStyl:hover>td {
  background-color:#00b4ed
}
</style>
